<template>
  <div>
    <Breadcrumb :opt-data="deviceTypeOptData"></Breadcrumb>
    <PageLayout>
      <div class="table-container height-100">
        <EZTable
          v-loading="tableLoading"
          :table-id="tableId"
          :table-hdl="tableHdl"
          :rows="deviceTypeData"
          :custom-empty="true"
          @pageChanged="getDeviceTypeData"
          @sizeChanged="getDeviceTypeData"
          @filterChange="getDeviceTypeData">
          <EmptyContent slot="empty" :opt-data="deviceTypeOptData"></EmptyContent>
        </EZTable>
      </div>
      <el-dialog
        :title="`${!isEditDeviceType ? '新增' : '编辑'}设备类别`"
        :visible.sync="showDeviceTypeDialog"
        :close-on-click-modal="false"
        width="600px"
        center>
        <el-form
          v-loading="deviceTypeFormLoading"
          :ref="deviceTypeFormRef"
          :model="deviceTypeForm"
          :rules="deviceTypeFormRules"
          size="small"
          label-width="130px">
          <el-form-item label="设备类别名" prop="name">
            <el-input v-model="deviceTypeForm.name" placeholder="请填写设备类别名"></el-input>
          </el-form-item>
          <el-form-item label="关联设备大类" prop="name">
            <el-select v-model="deviceTypeForm.deviceClass" clearable filterable class="width-100"
                       placeholder="请选择设备大类">
              <el-option :label="deviceClass.label" :value="deviceClass.value" :key="idx"
                         v-for="(deviceClass, idx) in deviceClassData"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="备注">
            <el-input type="textarea" v-model="deviceTypeForm.remarks" placeholder="请填写备注"></el-input>
          </el-form-item>
          <div class="text-align-right">
            <el-form-item>
              <el-button size="medium" @click="deviceTypeFormCanceled">取消</el-button>
              <el-button size="medium" type="primary" @click="deviceTypeFormSubmitted">提交</el-button>
            </el-form-item>
          </div>
        </el-form>
      </el-dialog>
    </PageLayout>
  </div>
</template>

<script>
  import {tableIdConfig, tableOptBtnConfig} from '@/config/table';
  import {msgCode} from "@/config/string";
  import {confirmHandle, deepCopyWithJson, messageHandle} from "@/utils";
  import {assembleTableOptBtn, getTableConfig, TableStateHdl} from "@/modules/routeParamStateHdl";
  import deviceTypeTableCfg from "../../config/table/deviceType";
  import EZTable from '../../components/table/EZTable';
  import {routerMeta} from "@/router/routerMeta";

  export default {
    name: "DeviceType",
    components: {
      EZTable
    },
    data() {
      return {
        tableLoading: true,
        tableId: tableIdConfig.deviceType,
        tableHdl: null,
        deviceTypeData: [],
        showDeviceTypeDialog: false,
        deviceTypeFormLoading: false,
        deviceTypeForm: {},
        deviceTypeFormRules: {
          name: [
            {required: true, message: '请填写设备类别名', trigger: 'blur'}
          ],
        },
        deviceTypeFormRef: 'deviceTypeFormRef',
        isEditDeviceType: false,
        deviceClassData: [],
      }
    },
    computed: {
      deviceTypeOptData() {
        return [
          {
            type: 'btn',
            label: '新增设备类型',
            icon: 'icon-tianjia',
            callback: () => {
              this.clickCreateBtn();
            }
          }
        ];
      }
    },
    activated() {
      this.initTableConfig();
      this.initDeviceTypeForm();
      this.getDeviceTypeData();
      this.getDeviceClassData()
    },
    methods: {
      initTableConfig() {
        if (this.tableHdl) return;
        const {columns = [], filters = []} = getTableConfig(this.tableId, deviceTypeTableCfg);
        assembleTableOptBtn(columns, ({type = '', data = {}}) => {
          if (!type) return;
          const deviceType = deepCopyWithJson(data);
          switch (type) {
            case tableOptBtnConfig.edit.type:
              this.showDeviceTypeDialog = true;
              this.isEditDeviceType = true;
              this.deviceTypeForm = deviceType;
              break;
            case tableOptBtnConfig.delete.type:
              this.deleteDeviceType(deviceType);
              break;
            default:
              break;
          }
        });
        this.tableHdl = new TableStateHdl(this.$route.name, this.tableId, columns, filters);
      },
      initDeviceTypeForm() {
        this.deviceTypeForm = {
          name: '',
          deviceClass: '',
          remarks: '',
        }
      },
      resetDeviceTypeForm() {
        this.initDeviceTypeForm();
        const deviceTypeForm = this.$refs[this.deviceTypeFormRef];
        deviceTypeForm && deviceTypeForm.resetFields();
      },
      clickCreateBtn() {
        this.isEditDeviceType && this.resetDeviceTypeForm();
        this.showDeviceTypeDialog = true;
        this.isEditDeviceType = false;
      },
      getDeviceClassData() {
        API.deviceClass.deviceClassAll().then(result => {
          const {data = []} = result;
          this.deviceClassData = data;
        }).catch(err => {
          console.log('err', err)
        });
      },
      getDeviceTypeData() {
        this.tableLoading = true;
        const selector = {};
        const tableParam = this.tableHdl.assembleTableParam();
        API.deviceType.deviceTypeList({...tableParam, selector}).then(result => {
          this.tableLoading = false;
          const {data = [], total = 0} = result;
          this.deviceTypeData = data;
          this.tableHdl.total = total;
        }).catch(err => {
          console.log('err', err)
          this.tableLoading = false;
        });
      },
      deleteDeviceType(deviceType = {}) {
        confirmHandle({label: `确定要删除设备类别：${deviceType.name} 吗?`}).then(() => {
          API.deviceType.deviceTypeDelete({_id: deviceType._id}).then(result => {
            messageHandle({code: msgCode.DELETE_SUCCESS, title: '设备类别'});
            this.tableHdl.judgeTableMatched();
            this.getDeviceTypeData();
            this.resetDeviceTypeForm();
          });
        }).catch(() => {
        });
      },
      deviceTypeFormCanceled() {
        this.showDeviceTypeDialog = false;
      },
      deviceTypeFormSubmitted() {
        this.$refs[this.deviceTypeFormRef].validate((valid) => {
          if (!valid) return;
          this.deviceTypeFormLoading = true;
          if (!this.isEditDeviceType) {
            API.deviceType.deviceTypeAdd({...this.deviceTypeForm}).then(result => {
              messageHandle({code: msgCode.ADD_SUCCESS, title: '设备类别'});
              this.showDeviceTypeDialog = false;
              this.deviceTypeFormLoading = false;
              this.getDeviceTypeData();
              this.resetDeviceTypeForm();
            }).catch(err => {
              console.log('err', err)
              this.deviceTypeFormLoading = false;
            });
          } else {
            API.deviceType.deviceTypeEdit({...this.deviceTypeForm}).then(result => {
              messageHandle({code: msgCode.EDIT_SUCCESS, title: '设备类别'});
              this.showDeviceTypeDialog = false;
              this.deviceTypeFormLoading = false;
              this.getDeviceTypeData();
              this.resetDeviceTypeForm();
            }).catch(err => {
              console.log('err', err)
              this.deviceTypeFormLoading = false;
            });
          }
        });
      },
    },
  }
</script>

<style scoped>

</style>
